#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstdio>

#define SIZE 1024

const std::string fifoname = "fifo";
const int defaultfd=-1;

class namepipe
{
public:
    namepipe(std::string name) : _name(name), _fd(defaultfd){}
    ~namepipe() {}
    bool Create()
    {
        int n = mkfifo(_name.c_str(), 0666);
        if(n==0)
        {
            std::cout<<"mklfifo success"<<std::endl;
        }
        else
        {
            std::cerr << "mkfifo error" << std::endl;
            return false;
        }
        return true;
    }
    void Close()
    {
        if(_fd==defaultfd)
        return ;
        else
        close(_fd);
    }
    bool OpenForRead()
    {
        _fd=open(fifoname.c_str(),O_RDONLY);
        if(_fd<0)
        {
            perror("open");
            return false;
        }  
        return true;
    }
     bool OpenForWrite()
    {
        _fd=open(fifoname.c_str(),O_WRONLY);
        if(_fd<0)
        {
            perror("open");
            return false;
        }  
        return true;
    }
    bool Read(std::string *out)
    {
        char buffer[SIZE]={0};
        ssize_t num=read(_fd,buffer,sizeof(buffer)-1);
        if(num>0)
        {
            buffer[num]=0;
            *out=buffer;
        }
        else 
        {
            return false; 
        }
        return true;
    }
    void Write(std::string & in)
    {
        write(_fd,in.c_str(),in.size()); 
    }
    void Remove()
    {
        int m=unlink(fifoname.c_str());
        (void)m;
    }

private:
    std::string _name;
    int _fd;
};